<script setup>
import { nextTick, reactive, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";
import schoolApi from "@/api/schoolApi";
import planApi from "@/api/planApi";
import scoreTemplateApi from "@/api/scoreTemplateApi";
const router = useRouter();

const submitForm = ref();
const searchForm = ref();
const searchModel = reactive({
  examFlag: false
});
let submitData = ref({
  planRuleType: "1",
  dates: [],
  examFlag: false,
  selectClassesList: [],
});
const visible = ref(false);
const submiting = ref(false);

const loading = ref(false);
let gradeList = ref([]);
let schoolData = ref([]);
let templates = ref([]);
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 17,
  showPageSize: true,
  pageSizeOptions: [17, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search();
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search();
  },
});

const columns = [
  {
    title: "班级名称",
    dataIndex: "name",
  },
  {
    title: "班级编号",
    dataIndex: "code",
  },
  {
    title: "学生人数",
    slotName: "studentCount",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];
const data = ref([]);

const showAddDialog = () => {
  visible.value = true;
  submitForm.value.resetFields();
};

const startEndDateChange = (dates) => {
  if (dates && dates.length == 2) {
    var startDate = dayjs(dates[0], "YYYY-MM-dd");
    var startMonth = startDate.month();
    submitData.value.startDate = dates[0];
    submitData.value.endDate = dates[1];
    if (startMonth + 1 >= 9) {
      submitData.value.schoolYear = startDate.year().toString();
    } else {
      submitData.value.schoolYear = (startDate.year() - 1).toString();
    }
  } else {
    submitData.value.schoolYear = "";
    submitData.value.startDate = "";
    submitData.value.endDate = "";
  }
};

const skipPlanManager = (plan) => {
  var params = {
    planId: plan.id,
    code: plan.code,
    name: plan.name,
    state: plan.state,
    startDate: plan.startDate,
    endDate: plan.endDate,
    examFlag: plan.examFlag,
    templateId: plan.templateId
  };
  router.push({
    name: "planManager",
    state: {
      params,
    },
  });
};



const clearDates = () => {
  submitData.value.schoolYear = "";
  submitData.value.startDate = "";
  submitData.value.endDate = "";
};

const editRecord = (record) => {
  visible.value = true;
  nextTick(() => {
    submitForm.value.resetFields();
    submitData.value = Object.assign({}, record);
  });
};

const deleteRecord = (record) => {
  planApi
    .delete({
      id: record.id,
    })
    .then((res) => {
      search();
    });
};

const handleSubmitSuccess = (values, e) => {
  submiting.value = true;
  planApi.save(values).then((res) => {
    visible.value = false;
    Message.success("保存成功");
    search();
    submiting.value = false;
  }).catch(() => {
    submiting.value = false;
  });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  planApi.page(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const searchKey = ref('');

const changeAll = (checked) => {
  if (checked) {
    submitData.value.selectClassesList = allClassesIds;
  } else {
    submitData.value.selectClassesList = [];
  }
}

const classesFilterData = computed(() => {
  if (!searchKey.value) return schoolData.value;
  return searchClassesData(searchKey.value);
})

const searchClassesData = (keyword) => {
  const loop = (data) => {
    const result = [];
    data.forEach(item => {
      if (item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          })
        }
      }
    })
    return result;
  }

  return loop(schoolData.value);
}

const loadSchoolData = ref(false)
const getSchoolGradeClassesList = () => {
  loadSchoolData.value = true
  schoolApi.getSchoolGradeClassesList().then((res) => {
    schoolData.value = res;
    loadSchoolData.value = false
  });
};

const refresh = () => {
  search();
};

const reset = () => {
  searchForm.value.resetFields();
};

const queryTemplates = () => {
  scoreTemplateApi.queryList().then(res => {
    templates.value = res;
  })
}

refresh();
queryTemplates();
getSchoolGradeClassesList();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>体测管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 8 }" :wrapper-col-props="{ span: 16 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="name" label="计划名称">
                  <a-input v-model="searchModel.name" placeholder="请输入计划名称" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="code" label="计划编码">
                  <a-input v-model="searchModel.code" placeholder="请输入计划编码" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="state" label="计划状态">
                  <a-select v-model="searchModel.state" placeholder="请选择计划状态">
                    <a-option value="">全部</a-option>
                    <a-option value="1">未开始</a-option>
                    <a-option value="2">进行中</a-option>
                    <a-option value="3">已结束</a-option>
                    <a-option value="4">已关闭</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search()">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">

              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <a-spin :loading="loading" style="width: 100%" tip="正在加载...">
      <a-card style="margin-top: 16px; width: 100%" :body-style="{ padding: '0px' }" title="计划列表">
        <div style="min-height: 300px; background-color: #fff; padding: 16px">
          <a-grid :cols="{ xs: 1, sm: 2, md: 2, lg: 2, xl: 3, xxl: 5 }" :colGap="16" :rowGap="16">
            <a-grid-item>
              <a-card hoverable :style="{ width: '100%', height: '198px' }" class="empty-card-wrap"
                @click="showAddDialog">
                <div class="flex flex-column flex-center" style="height: 100%">
                  <div><icon-plus size="20"></icon-plus></div>
                  <div style="margin-top: 20px">点击体测计划</div>
                </div>
              </a-card>
            </a-grid-item>
            <a-grid-item v-for="plan in data" :key="plan.id" @click.stop="skipPlanManager(plan)">
              <a-card hoverable class="plan-card-hover"
                :style="{ width: '100%', height: '198px', border: 'none', cursor: 'pointer', borderRadius: '16px', background: 'linear-gradient(140deg, #ffffff 0%, #f0f7ff 45%, #e6f0ff 100%)' }"
                :body-style="{ paddingTop: '4px' }" :header-style="{ borderBottom: '0px', paddingBottom: '0px' }"
                :title="plan.name">
                <template #title>
                  <div class="flex  flex-v-center">
                    <img src="../../assets/资源计划大图.png" style="width: 25px;height: 25px;" alt="">
                    <div class="plan-title-text" style="margin-left: 10px;font-weight: 600;">{{ plan.name }}</div>
                  </div>
                </template>
                <div>
                  <a-space>
                    <a-tag size="small" bordered :color="plan.state <= 1 ? 'orange' : 'blue'"> {{ plan.stateDesc
                      }}</a-tag>
                  </a-space>
                </div>
                <div style="padding-top: 15px">
                  <div class="plan-detail-item">
                    计划编码<span style="padding-left: 10px; color: #111111">{{
                      plan.code
                    }}</span>
                  </div>
                  <div class="plan-detail-item">
                    <div class="flex" style="color: #999">
                      <div>
                        <div>学校数量(所)</div>
                        <div style="
                            font-size: 18px;
                            font-weight: 600;
                            color: #111111;
                            padding-top: 5px;
                          ">
                          {{ plan.schoolNum }}
                        </div>
                      </div>
                      <div style="margin-left: 20px">
                        <div>学生数量（人）</div>
                        <div style="
                            font-size: 18px;
                            font-weight: 600;
                            color: #111111;
                            padding-top: 5px;
                          ">
                          {{ plan.studentNum }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="plan-detail-item">
                    起止时间<span style="padding-left: 15px; color: #111111">{{
                      plan.startDate + " 至 " + plan.endDate
                    }}</span>
                  </div>
                </div>
              </a-card>
            </a-grid-item>
          </a-grid>
        </div>
        <div class="flex flex-end" style="
            margin-top: 16px;
            background-color: #fff;
            padding: 0 16px 16px 0;
          ">
          <a-pagination :total="pagination.total" show-page-size show-jumper
            :page-size-options="pagination.pageSizeOptions" :page-size="pagination.pageSize"
            :current="pagination.current" @change="pagination.pageChange"
            @page-size-change="pagination.pageSizeChange" />
        </div>
      </a-card>
    </a-spin>
  </div>
  <a-modal v-model:visible="visible" width="1000px" title="新增计划" :footer="null">
    <a-spin :loading="loadSchoolData" style="width: 100%;">
      <a-form ref="submitForm" size="large" :model="submitData" @submit-success="handleSubmitSuccess" auto-label-width>
        <a-row>
          <a-col :span="12">
            <a-form-item field="name" label="计划名称" :rules="[{ required: true, message: '请输入计划名称' }]">
              <a-input v-model="submitData.name" placeholder="请输入计划名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="startDate" label="起止时间" :rules="[{ required: true, message: '请选择起止时间' }]">
              <a-range-picker v-model="submitData.dates" @change="startEndDateChange" @clear="clearDates" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="templateId" label="评分标准模板" :rules="[{ required: true, message: '请选择评分模板' }]">
              <a-select v-model="submitData.templateId" placeholder="请选择评分模板">
                <a-option v-for="item in templates" :key="item.id" :label="item.name" :value="item.id"></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="schoolYear" label="体测计划所属学年" :rules="[{ required: true, message: '请先选择起止时间' }]">
              <a-input v-model="submitData.schoolYear" disabled style="margin-right: 16px"
                placeholder="自动根据计划起止时间生成，无需输入" />
              <a-popover position="rb">
                <icon-question-circle-fill size="20" style="color: #00aaff" />

                <template #content>
                  <p>
                    计划所属学年根据计划开始时间自动生成，修改体测计划开始时间可自动修改计划对应的学年
                  </p>
                  <p>
                    例如：2022年9月1日之后，2023的9月1日之前，新增的体测计划为2022学年
                  </p>
                </template>
              </a-popover>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="planRuleType" label="成绩选取规则">
              <a-radio-group v-model="submitData.planRuleType">
                <a-radio value="1">最新成绩</a-radio>
                <a-radio value="2">最好成绩</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="testAddress" label="体测地点">
              <a-input v-model="submitData.testAddress" placeholder="请输入体测地点" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="openReservation" label="开放预约">
              <a-switch v-model="submitData.openReservation" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="selectClassesList" label="体测对象">
          <div class="custom-transfer" style="height: 450px;">
            <a-input-search placeholder="请输入学校名称搜索" style="margin-bottom: 8px; max-width: 580px" v-model="searchKey" />
            <a-card style="width: 580px;height: 450px;overflow: auto;">
              <template #title>选择测试班级</template>
              <template #extra>
                <a-checkbox @change="changeAll">全选</a-checkbox>
              </template>
              <a-tree :checkable="true" v-model:checked-keys="submitData.selectClassesList" blockNode
                checked-strategy="child" :fieldNames="{ key: 'id', title: 'name' }" :data="classesFilterData">
              </a-tree>
            </a-card>
          </div>
        </a-form-item>
        <a-form-item style="margin-top: 40px;" :label-col-props="{ span: 4 }">
          <a-space>
            <a-button :loading="submiting" html-type="submit" type="primary">保存</a-button>
            <a-button @click="() => {
              visible = false;
            }
              ">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<style scoped>
.plan-detail-item {
  font-size: 12px;
  color: #999;
  padding-bottom: 15px;
}

.empty-card-wrap {
  background: linear-gradient(140deg, #ffffff 0%, #f0f7ff 45%, #e6f0ff 100%);
  border-radius: 16px;
  transition: all 0.3s ease;
  border: 2px dashed #e5e6eb;
}

.empty-card-wrap:hover {
  border-color: #165DFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(22, 93, 255, 0.1);
}

/* 添加卡片hover样式 */
.plan-card-hover {
  transition: all 0.3s ease;
  border: 1px solid transparent !important;
}

.plan-card-hover:hover {
  border: 1px solid #165DFF !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(22, 93, 255, 0.12);
}
</style>
